<?php
/**
 * $Id:$
 *
 * FGS is the legal property of its developers, whose names are too numerous
 * to list here.  Please refer to the COPYRIGHT file distributed with this
 * source distribution.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */ 


class fgsGames {

	var $cache = array();

	/** 
	 * get() return a game information
	 */
	function get($id = null, $hide_disabled = false) {

		if ($id != null && isset($this->cache[$id])) 
			return $this->cache[$id];

		$where = array();
		if (!empty($id))
			$where[] = sprintf('gid = "%s"', fgsSql::escapeStr($id));
		if ($hide_disabled)
			$where[] = 'NOT is_disabled';

		$query = sprintf('
			SELECT *
			FROM fgs_games 
			%s
			ORDER BY is_disabled, name',
			count($where) ? 'WHERE '.implode(' AND ', $where) : ''
		);
				
		$sql = fgs::sql();
		$sql->query($query);
		$infos = $sql->fetchAll();
		if ($id != null) {
			$infos = current($infos);
			if ($this)
				$this->cache[$id] = $infos;
		}
		return $infos;
	}

	/**
	 * getById() return a game by id
	 */
	function getById($id) {
		$query = sprintf('SELECT * FROM fgs_games WHERE id=%d', $id);
		$sql = fgs::sql();
		$sql->query($query);
		if (!$sql->nbrows())
			return false;
		return $sql->getline();
	}

	/**
	 * add() add a game into database
	 */
	function add($name, $description, $url, $version_cmd, $launch_cmd, $gid, $port, $is_disabled) {
		$query = sprintf('
			INSERT INTO fgs_games
			SET 
				name = "%s",
				description = "%s",
				url = "%s",
				version_cmd = "%s",
				launch_cmd = "%s",
				gid = "%s",
				port = %d,
				is_disabled = %d',
			fgsSql::escapeStr($name),
			fgsSql::escapeStr($description),
			fgsSql::escapeStr($url),
			fgsSql::escapeStr($version_cmd),
			fgsSql::escapeStr($launch_cmd),
			fgsSql::escapeStr($gid),
			$port,
			$is_disabled ? 1 : 0
		);

		$sql = fgs::sql();
		$sql->query($query);
		return $sql->getLastId();
	}

	/**
	 * update() add a game into database
	 */
	function update($id, $name, $description, $url, $version_cmd, $launch_cmd, $gid, $port, $is_disabled) {
		$query = sprintf('
			UPDATE fgs_games
			SET 
				name = "%s",
				description = "%s",
				url = "%s",
				version_cmd = "%s",
				launch_cmd = "%s",
				gid = "%s",
				port = %d,
				is_disabled = %d
			WHERE
				id = %d',
			fgsSql::escapeStr($name),
			fgsSql::escapeStr($description),
			fgsSql::escapeStr($url),
			fgsSql::escapeStr($version_cmd),
			fgsSql::escapeStr($launch_cmd),
			fgsSql::escapeStr($gid),
			$port,
			$is_disabled ? 1 : 0,
			$id
		);

		$sql = fgs::sql();
		return $sql->query($query) ? true : false;
	}

	/**
	 * enable() enable a game 
	 */
	function enable($id, $enable) {
		$query = sprintf('
			UPDATE fgs_games
			SET 
				is_disabled = %d
			WHERE
				id = %d',
			$enable ? 0 : 1,
			$id
		);

		$sql = fgs::sql();
		return $sql->query($query) ? true : false;
	}

	/**
	 * exist() test if game exist
	 * @param gid gid of game
	 */
	function exist($gid) {
		$query = sprintf('
			SELECT gid
			FROM fgs_games
			WHERE 
				gid = "%s"
				AND NOT is_disabled',
			fgsSql::escapeStr($gid)
		);

		$sql = fgs::sql();
		$sql->query($query);

		return $sql->nbrows();
	}

	/**
	 * getServers() get server list for a game
	 * @param gid valid gid of game
	 */
	function getServers($gid) {
		$query = sprintf('
			SELECT ffg.name as game_name,
				ffg.version as game_version,
				ff.fgsd_ip as host,
				ffg.port as port,
				ff.fgsd_name as fgs
			FROM fgs_fgsd_games ffg
			INNER JOIN fgs_fgsd ff
				ON ffg.id_fgsd = ff.id
			WHERE
				ffg.name = "%s"
				AND NOT ffg.is_deleted
			GROUP BY game_name, port, fgs
			ORDER BY ffg.id DESC',
			fgsSql::escapeStr($gid)
		);
		
		$sql = fgs::sql();
		$sql->query($query);

		return $sql->fetchAll();
	}

	/**
	 * getLogo() get logo from hash
	 * @param hash logo hash
	 */
	function getLogo($hash) {
		$query = sprintf('
			SELECT logo_data
			FROM fgs_games
			WHERE logo_hash = "%s"',
			fgsSql::escapeStr($hash)
		);

		$sql = fgs::sql();
		$sql->query($query);

		return $sql->getline();
	}

	/**
	 * updateLogo() update game logo
	 */
	function updateLogo($id, $filename) {
		$data = file_get_contents($filename);
		$im = imagecreatefromstring($data);
		$tim = imagecreatetruecolor(40, 40);
		if ($im && $tim) {
			imagealphablending($tim, false);
			imagesavealpha($tim, true);
			$transparent = imagecolorallocatealpha($tim, 255, 255, 255, 127);
			imagefilledrectangle($tim, 0, 0, 40, 40, $transparent);
			imagecopyresampled($tim, $im, 0, 0, 0, 0, 40, 40, imagesx($im), imagesy($im));
			ob_start();
			imagepng($tim);
			$data = ob_get_contents();
			ob_get_clean();
		} else return false;

		$hash = md5($data);
		$data = base64_encode($data);

		$query = sprintf('
			UPDATE fgs_games 
			SET 
				logo_hash = "%s",
				logo_data = "%s"
			WHERE 
				id = %d',
			$hash, 
			$data, 
			$id
		);

		$sql = fgs::sql();
		return $sql->query($query) ? true : false;
	}

	/**
	 * checkSession() check if game session exit
	 * @param sid game session
	 * @return array with game attributes, or false if failed.
	 */
	function checkSession($sid) {

		$query = sprintf('
			SELECT *
			FROM fgs_fgsd_games
			WHERE sid = "%s"', 
			fgsSql::escapeStr($str)
		);

		$sql = fgs::sql();
		$sql->query($query);

		if ($sql->nbrows() != 1)
			return false;

		return true;
	
	}

	/**
	 * register() register a game
	 * @param fgsd valid array of proxy (use fgsProxys::checkSession())
	 * @param name name of game
	 * @param version version of game
	 * @param port port of game
	 * @return string game session id
	 */
	function register($fgsd, $name, $version, $port) {

		// create sid
		$game_sid = md5(uniqid('k'));

		// add game to database
		$query = sprintf('
			INSERT INTO fgs_fgsd_games
			SET
				id_fgsd = "%d",
				sid = "%s",
				name = "%s",
				version = "%s",
				port = "%d",
				dt_create = NOW()',
			 $fgsd['id'],
			 fgsSql::escapeStr($game_sid),
			 fgsSql::escapeStr($name),
			 fgsSql::escapeStr($version),
			 $port
		 );

		$sql = fgs::sql();
		$sql->query($query);

		// check if failed
		if ($sql->getLastId() <= 0) {
			fgsLog::log(0, sprintf('[%s] failed when added server %s:%d, ver %s', $fgsd['fgsd_name'], addslashes($name), $port, addslashes($version)));
			return false;
		}
	
		fgsLog::log(0, sprintf('[%s] add %s (%s, port=%d, sid=%s)', $fgsd['fgsd_name'], addslashes($name), addslashes($version), $port, $game_sid));

		return $game_sid;

	}	

	/**
	 * unregister() unregister a game
	 * @param fgsd valid array of proxy (use fgsProxys::checkSession())
	 * @param sid valid game sid
	 * @return string game session id
	 */
	function unregister($fgsd, $sid) {

		// set deleted
		$query = sprintf('
			UPDATE fgs_fgsd_games
			SET
				is_deleted = 1,
				sid = ""
			WHERE
				sid = "%s"
				AND id_fgsd = "%d"',
			 $fgsd['id'],
			 fgsSql::escapeStr($sid)
		 );

		$sql = fgs::sql();
		$sql->query($query);

		// TODO: verify success of last query
		fgsLog::log(0, sprintf('[%s] delete %s', $fgsd['fgsd_name'], $sid));

		return true;

	}	
}

?>
